import { useState, useRef, useEffect } from 'react'
import { message } from 'antd'
import { ModalForm, ProFormText } from '@ant-design/pro-components'
import type { ProFormInstance } from '@ant-design/pro-components'
import { AddParamsFnc, ShowEditParamsFnc, EditParamsFnc } from '@/services/params'

const AddEdit = ({attrID, openType, isModalOpen, openBox, activeName, catID, getTable, cascaderValue}: any) => {
  const formRef: any = useRef<ProFormInstance>();
  // 用于做比较的form
  const [formObj, setFormObj] = useState({});
  
  const [messageApi, contextHolder] =  message.useMessage()

  // 打开编辑盒子 数据初始化
  const init = async () => {
    if(attrID !== '') {
        const res = await ShowEditParamsFnc(catID, attrID, {attr_sel: activeName})
        if(res.meta.status === 200) {
          formRef.current.setFieldsValue({attr_name: res.data.attr_name})
          setFormObj({attr_name: res.data.attr_name})
        } 
      }
  }
  useEffect(() => { init() }, [attrID])

  // 公告提示消息
  const publicMsg = (msg: string) => {
    messageApi.success(msg, 1.5, () => {
     openBox(false)
     getTable(cascaderValue, activeName)
    })
  }

  // 添加（动态参数 或 静态属性） 修改（动态参数 或 静态属性）
  const onFinish = async (value: {attr_name: string}) => {
    if(openType === 'add') {
      const res = await AddParamsFnc(catID, {attr_name: value.attr_name, attr_sel: activeName})
      if(res.meta.status === 201) {
        publicMsg('添加成功')
      }
    } else {
       if(JSON.stringify(value) === JSON.stringify(formObj)) { // 未修改
        return 
       } else {
        const res = await EditParamsFnc(catID, attrID, {attr_name: value.attr_name, attr_sel: activeName})
        if(res.meta.status === 200) publicMsg('修改成功')
       }
    }
  }  

  return (
    <>
    {contextHolder}
    <ModalForm
      title={activeName === 'many' ? (openType=== 'add' ? '添加' : '修改' ) + '动态参数' : (openType=== 'add' ? '添加' : '修改') + '静态属性'}
      formRef={formRef}
      width={500}
      layout="horizontal"
      labelCol={{ span: 4 }}
      open={isModalOpen}
      onFinish={(val: any) => onFinish(val)}
      modalProps={{ onCancel: () => openBox(false) }}
    >
      <ProFormText
        name="attr_name"
        label={activeName === 'many' ? '动态参数' : '静态属性'}
        rules={[
          { required: true, message: `请输入${activeName === 'many' ? '动态参数' : '静态属性'}` },
          { min: 3, max: 10, message: '长度在3-10个字符' },
        ]}
      />
    </ModalForm>
    </>
  )
}

export default AddEdit